import { http } from '@/utils/request'
import config from '@/utils/request'

// 微信登录
export const wxLogin = (code) => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      success: async (loginRes) => {
        try {
          // 获取用户信息
          const userInfo = await getUserProfile();
          
          // 调用后端微信登录接口
          const res = await http.post('/auth/login/wechat', {
            code: loginRes.code,
            nickname: userInfo.nickName,
            avatar: userInfo.avatarUrl,
            gender: userInfo.gender === 1 ? '男' : '女',
            country: userInfo.country,
            province: userInfo.province,
            city: userInfo.city,
            language: userInfo.language
          });
          
          console.log('微信登录响应:', res);
          
          if (res.code === 200 && res.data) {
            // 保存token和用户信息
            const { accessToken, refreshToken, user } = res.data;
            uni.setStorageSync('accessToken', accessToken);
            uni.setStorageSync('refreshToken', refreshToken);
            uni.setStorageSync('userInfo', user);
            
            resolve(res.data);
          } else {
            reject(new Error(res.message || '登录失败'));
          }
        } catch (error) {
          console.error('微信登录失败:', error);
          reject(error);
        }
      },
      fail: (err) => {
        console.error('微信登录失败:', err);
        reject(err);
      }
    });
  });
}

// 获取用户信息
const getUserProfile = () => {
  return new Promise((resolve, reject) => {
    uni.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        resolve(res.userInfo);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 密码登录
export const passwordLogin = (data) => {
  return http.post('/auth/login/password', data);
}

// 短信验证码登录
export const smsLogin = (data) => {
  return http.post('/auth/login/sms', data);
}

// 发送短信验证码
export const sendSmsCode = (phonenumber) => {
  return http.post('/sms/code', { phonenumber });
}

// 刷新token
export const refreshToken = () => {
  const refreshToken = uni.getStorageSync('refreshToken');
  if (!refreshToken) {
    return Promise.reject(new Error('未找到刷新令牌'));
  }
  
  return http.post('/auth/refresh', null, {
    headers: {
      'Authorization': `Bearer ${refreshToken}`
    }
  });
} 